﻿namespace WebCommon.Extensions
{
    using System;
    using System.IO;
    using System.Web;

    using WebCommon.IO;

    public class ExJsonReturn : JsonReturn
    {
        /// <summary>
        /// 异常信息
        /// </summary>
        public string Message { get; protected set; }
        /// <summary>
        /// 获取调用堆栈上直接帧的字符串表示形式。
        /// </summary>
        public string StackTrace { get; protected set; }
        /// <summary>
        /// 设置日志目录,默认~/Log/
        /// </summary>
        public string FilePath { get; protected set; }

        public ExJsonReturn()
        {

        }

        static string GetFilePath()
        {
            DateTime dateTime = DateTime.Now;
            return dateTime.ToString("yyyyMMdd") + "/" + dateTime.Ticks + ".txt";
        }

        public ExJsonReturn(Exception ex)
            : base()
        {
            this.FilePath = HttpContext.Current.Server.MapPath("~/Log/");
            this.Code = "99";
            this.CodeMs = "服务器异常";
            this.ModelData = ex.Message;
            this.Message = ex.Message;
            this.StackTrace = ex.StackTrace;
        }

        /// <summary>
        /// 保存异常到日志
        /// </summary>
        public void Save()
        {
            var p = this.FilePath + GetFilePath();
            FileOperation.CreateDirectory(p);
            File.WriteAllText(p, this.ModelData.ToString());
        }

    }
}